package org.melanesia.beans;

import java.util.Map;

import org.melanesia.converters.JavaToJavaConverter;



public class PropertyMapper {
    
	public void setProperty(Object bean, String propertyName, Object value, Mapper sqlMapper) {
		setProperty(bean, propertyName, value, sqlMapper, null);
	}
	    
    public void setProperty(Object bean, String propertyName, Object value, Mapper sqlMapper, Map<String, Class<?>> beanClassMapping) {
        PropertyAccessor accessor = AccessorFactory.createAccessor(bean.getClass(), propertyName);
        
        Class<?> propertyClass = accessor.getPropertyClass();
        
        if (value != null) {
            JavaToJavaConverter converter = sqlMapper.findJavaToJavaConverter(value.getClass(), propertyClass);
            if (converter != null) {
                value = converter.convert(value);
            }
        }
        
        accessor.set(bean, value, beanClassMapping);
    }

    @SuppressWarnings("unchecked")
    public <T> T getProperty(Object bean, String propertyName) {
        PropertyAccessor accessor = AccessorFactory.createAccessor(bean.getClass(), propertyName);
        return (T)accessor.get(bean);
    }
}
